// app.js
const { formatObjToUrl } = require('./utils/util')

App({
  onLaunch() {
    // 每次启动小程序，获取登录code
    this.getLoginCode()
  },

  // 获取登录code
  getLoginCode() {
    wx.login({
      success: res => {
        this.handleLogin(res.code)
      }
    })
  },

  // 登录获取openId
  handleLogin(code) {
    const submitData = { code }
    this.axios({
      url: `/study/login${formatObjToUrl(submitData)}`,
    }).then(res => {
      if(res.code === 0) {
        this.globalData.openId = res.result;
      }
    })
  },

  // 封装wx.request
  axios({ url, method = "GET", data = {} }) {
    return new Promise((resolve, reject) => {
      wx.request({
        url: `${this.globalData.baseUrl}${url}`,
        method,
        data,
        header: {
          'Authorization': this.globalData.openId
        },
        success: function (res) {
          if(res.data.code !== 0) {
            wx.showToast({
              title: res.data.message,
              icon: 'error',
              duration: 2000
            })
          }
          resolve(res.data);
        },
        fail: function (res) {
          wx.showToast({
            title: '网络请求异常',
            icon: 'error',
            duration: 2000
          })
        }
      })
    })
  },
  globalData: {
    userInfo: null,
    baseUrl: 'http://192.168.1.143:8080/vxapi',
    openId: ''
  }
})